package net.weitalk.metrics.v2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class RedisMetricsStorage implements MetricsStorage {
    //mocked storage
    private Map<String, List<RequestInfo>> storage = new HashMap<>();
    
    @Override
    public void saveRequestInfo(RequestInfo requestInfo) {
        String apiName = requestInfo.getApiName();
        storage.putIfAbsent(apiName, new ArrayList<RequestInfo>());
        storage.get(apiName).add(requestInfo);
    }

    @Override
    public List<RequestInfo> getRequestInfos(String apiName, long startTimeInMillis, long endTimeInMillis) {
        return storage.get(apiName)
                .stream()
                .filter(
                    requestInfo -> requestInfo.getTimestamp() > startTimeInMillis && 
                            requestInfo.getResponseTime() < endTimeInMillis - startTimeInMillis
                )
                .collect(Collectors.toList());
    }

    @Override
    public Map<String, List<RequestInfo>> getRequestInfos(long startTimeInMillis, long endTimeInMillis) {
        Map<String, List<RequestInfo>> requestInfos = new HashMap<>();
        for (String apiName : storage.keySet()) {
            requestInfos.putIfAbsent(apiName, getRequestInfos(apiName, startTimeInMillis, endTimeInMillis));
        }
        return requestInfos;
    }
}
